package org.itboys.mobile.service.mongo.site;

import org.apache.commons.lang.StringUtils;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.entity.mongo.SundayMemberRecord;
import org.itboys.mobile.entity.mysql.product.SundayProductCategory;
import org.itboys.mobile.entity.mysql.product.SundayProductRecord;
import org.itboys.mobile.service.mongo.web.SundayPermissionService;
import org.itboys.mobile.service.mongo.web.SundayRecordPermissionService;
import org.itboys.mobile.service.mysql.site.SundaySiteProductRecordService;
import org.itboys.mobile.service.mysql.web.product.SundayProductCategoryService;
import org.itboys.mobile.util.Md5UtilJx;
import org.itboys.mobile.util.NameUtil;
import org.itboys.mobile.util.NumberUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：zzq
 * 时间：2017/10/25
 * 描述：雄安加盟网_前端_用户记录相关
 */
@Service
public class SundaySiteMemberRecordService extends BaseMongoService<SundayMemberRecord>{
    @Resource(name = "mobileDs")
    private MongoDataSource mobileDataSource;
    @Autowired
    private JoinSiteValidateCodeService codeService;
    @Autowired
    private SundayProductCategoryService categoryService;
    @Autowired
    private SundayRecordPermissionService recordPermissionService;
    @Autowired
    private SundaySiteProductRecordService productRecordService;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mobileDataSource;
    }

    @Override
    protected Class<SundayMemberRecord> getEntityClass() {
        return SundayMemberRecord.class;
    }

    /**
     * 前端注册
     * @param userType
     * @param userName
     * @param password
     * @param nickName
     * @param brandName
     * @param businessType
     * @param categoryId
     * @param categoryName
     * @param mobileName
     * @param mobile
     * @param phone
     * @param code
     */
    @Transactional
    public void save(Integer userType,String userName,String password,String nickName,String brandName,String businessType,
                     Long categoryId,String categoryName,String mobileName,String mobile,String phone,String code){
        Map<String,Object> param = new HashMap<String, Object>();
        //1,校验验证码
        //codeService.checkValidateCode(phone, code);
        checkMemberIsExist(phone,userName);
        SundayProductRecord productRecord=new SundayProductRecord();
        SundayProductCategory parent=categoryService.find(categoryService.find(categoryId).getParentId());
        productRecord.setCategoryId(categoryId);
        productRecord.setCategoryName(categoryName);
        productRecord.setParentId(parent.getId());
        productRecord.setParentName(parent.getName());
        SundayMemberRecord memberRecord=new SundayMemberRecord();
        memberRecord.setUserName(userName);
        memberRecord.setPassword(Md5UtilJx.GetMD5Code(password));
        memberRecord.setNickName(nickName);
        memberRecord.setBrandName(brandName);
        memberRecord.setBusinessType(businessType);
        memberRecord.setCategoryId(categoryId);
        memberRecord.setCategoryName(categoryName);
        memberRecord.setParentId(parent.getId());
        memberRecord.setParentName(parent.getName());
        memberRecord.setMobileName(mobileName);
        memberRecord.setMobile(mobile);
        memberRecord.setPhone(phone);
        memberRecord.setUserType(userType);
        memberRecord.setStatus(1);
        try{
            productRecordService.insert(productRecord);
            super.save(memberRecord);
            recordPermissionService.saveRecordPermission(memberRecord.getId(),null,productRecord.getId(),1,false);
        }catch (Exception e){
            //如果出现异常则删除
            if(LongUtil.isNotZreo(memberRecord.getId())){
                super.delete(memberRecord.getId());
            }
            if(LongUtil.isNotZreo(productRecord.getId())){
                productRecordService.delete(productRecord.getId());
            }
            throw new ErrorException("网络异常");
        }
    }

    /**
     *
     * @param password
     * @param phone
     * @param code
     * @param sex
     */
    public void save(String phone,String password,String code,String sex){
        Map<String,Object> param = new HashMap<String, Object>();
        //1,校验验证码
        codeService.checkValidateCode(phone, code);
        checkMemberIsExist(phone,null);
        SundayMemberRecord memberRecord=new SundayMemberRecord();
        memberRecord.setPhone(phone);
        memberRecord.setUserType(SundayCommonConstants.user_type_member);
        memberRecord.setSex(sex);
        memberRecord.setPassword(Md5UtilJx.GetMD5Code(password));
        super.save(memberRecord);
    }

    public void batchSave(Long  categoryId){
        for(int i=0;i<20;i++){
            SundayMemberRecord memberRecord=new SundayMemberRecord();
            memberRecord.setUserName(NumberUtil.generateNumber(String.valueOf(categoryId)));
            memberRecord.setPassword(Md5UtilJx.GetMD5Code("123"));
            memberRecord.setUserType(2);
            memberRecord.setStatus(1);

            SundayProductCategory category=categoryService.find(categoryId);
            SundayProductCategory parent=categoryService.find(categoryService.find(categoryId).getParentId());
            memberRecord.setCategoryId(categoryId);
            memberRecord.setCategoryName(category.getName());
            memberRecord.setParentId(parent.getId());
            memberRecord.setParentName(parent.getName());

            SundayProductRecord productRecord=new SundayProductRecord();
            productRecord.setCategoryId(categoryId);
            productRecord.setCategoryName(category.getName());
            productRecord.setParentId(parent.getId());
            productRecord.setParentName(parent.getName());

            productRecordService.insert(productRecord);
            super.save(memberRecord);
            recordPermissionService.saveRecordPermission(memberRecord.getId(),null,productRecord.getId(),1,false);
        }


    }


    /**
     * 修改密码
     * @param phone
     * @param password
     * @param code
     */
    public void changePassword(String phone,String password,String code){
        Map<String,Object> param = new HashMap<String, Object>();
        SundayMemberRecord memberRecord=null;
        codeService.checkValidateCode(phone, code);
        param.clear();
        param.put("phone", phone);
        param.put("isDeleted", SundayCommonConstants.NO);
        List<SundayMemberRecord> members=super.list(param);
        if(ListUtil.isNotNull(members)){
            memberRecord=members.get(0);
            memberRecord.setPassword(Md5UtilJx.GetMD5Code(password));
            super.updateExceptEmpty(memberRecord.getId(),memberRecord);
        }else {
            throw  new ErrorException("该手机号未注册");
        }

    }

    /**
     * 登录
     * @param loginType
     * @param userName
     * @param phone
     * @param password
     * @return
     */
    public SundayMemberRecord login(Integer loginType,String userName,String phone,String password){
        Map<String,Object> param = new HashMap<String, Object>();
        if(loginType==1){
            //1,校验用户名
            param.put("phone", phone);
            param.put("isDeleted", SundayCommonConstants.NO);
            if(ListUtil.isNull(super.list(param))){
                throw new ErrorException("手机号未注册");
            }
            param.clear();
            param.put("phone", phone);
            param.put("password", Md5UtilJx.GetMD5Code(password));
            param.put("isDeleted", SundayCommonConstants.NO);
            List<SundayMemberRecord> oldMembers = super.list(param);
            if(ListUtil.isNull(oldMembers)){
                throw new ErrorException("密码错误或用户被注销");
            }else{
                //3，组装结果
                SundayMemberRecord memberRecord=oldMembers.get(0);
                if(memberRecord.getUserType()!=loginType){
                    throw new ErrorException("登录类型错误");
                }
                return memberRecord;
            }
        }else if(loginType==2){
            //1,校验用户名
            param.put("userName", userName);
            param.put("isDeleted", SundayCommonConstants.NO);
            if(ListUtil.isNull(super.list(param))){
                throw new ErrorException("不存在的用户名");
            }
            param.clear();
            param.put("userName", userName);
            param.put("password", Md5UtilJx.GetMD5Code(password));
            param.put("isDeleted", SundayCommonConstants.NO);
            List<SundayMemberRecord> oldMembers = super.list(param);
            if(ListUtil.isNull(oldMembers)){
                throw new ErrorException("密码错误或用户被注销");
            }else{
                //3，组装结果
                SundayMemberRecord memberRecord=oldMembers.get(0);
                if(memberRecord.getUserType()!=loginType){
                    throw new ErrorException("登录类型错误");
                }
                return memberRecord;
            }
        }
        return null;
    }
    @Transactional
    public void updateDataBusiness(Long businessId,Long productId,String nickName,
                                   //企业部分
                                   String mobileName,String phone,String mobile,String email,String qqNumber,String faxNumber,String englishName,String businessSite,String businessType,String generateTime,String corporation,String amount,
                                   Long provinceId,String provinceName,Long cityId,String cityName,Long districtId,String districtName,String address,
                                   String creditNum,String licenseNum,String taxNum,String institutionalNum,
                                   String brandName,String brandEnglishName,String brandLogo,String brandSource,String brandGenerateTime,String brandRegisterNum,
                                   //项目部分
                                   String productName,String productViceName,String keyWord,String desc,
                                   String investAmount,String joinModel,String joinArea,Integer isAreaAuthorization,String limitTime,Integer directShopNum,Integer joinShopNum,Integer isBusinessBack,String products,
                                   String managerModel,String fitPerson,String image
    ){

        //项目部分
        SundayProductRecord product=productRecordService.find(productId);
        product.setName(productName);product.setViceName(productViceName);product.setKeyWord(keyWord);product.setDesc(desc);
        product.setInvestAmount(investAmount);product.setJoinModel(joinModel);product.setJoinArea(joinArea);product.setBrandSource(brandSource);product.setIsAreaAuthorization(isAreaAuthorization);product.setLimitTime(limitTime);
        product.setDirectShopNum(directShopNum);product.setJoinShopNum(joinShopNum);product.setIsBusinessBack(isBusinessBack);product.setProducts(products);
        product.setManagerModel(managerModel);product.setFitPerson(fitPerson);product.setImage(image);
        //更新后状态为待审核状态
        product.setStatus(1);
        productRecordService.update(product);
        //企业部分
        SundayMemberRecord business=super.getById(businessId);
        business.setNickName(nickName);business.setMobileName(mobileName);business.setPhone(phone);business.setMobile(mobile);business.setEmail(email);business.setQqNumber(qqNumber);business.setFaxNumber(faxNumber);business.setEnglishName(englishName);business.setBusinessSite(businessSite);business.setBusinessType(businessType);business.setGenerateTime(generateTime);business.setCorporation(corporation);
        business.setAmount(amount);business.setProvinceId(provinceId);business.setProvinceName(provinceName);business.setCityId(cityId);business.setCityName(cityName);business.setDistrictId(districtId);business.setDistrictName(districtName);business.setAddress(address);
        business.setCreditNum(creditNum);business.setLicenseNum(licenseNum);business.setTaxNum(taxNum);business.setInstitutionalNum(institutionalNum);
        business.setBrandName(brandName);business.setBrandEnglishName(brandEnglishName);business.setBrandLogo(brandLogo);business.setBrandSource(brandSource);business.setBrandGenerateTime(brandGenerateTime);business.setBrandRegisterNum(brandRegisterNum);
        //更新后状态为待审核状态
        business.setStatus(1);
        super.updateExceptEmpty(businessId,business);
    }

    /**
     * 企业资质审核相关内容
     * @param businessId
     * @param licenseImg
     * @param institutionalImg
     * @param taxImg
     * @param brandRegisterImg
     * @param businessBackImg
     * @param patentImg
     */
    public void  updateDataBusiness(Long businessId,String licenseImg,String institutionalImg,String taxImg,String  brandRegisterImg,String businessBackImg,String patentImg){
        SundayMemberRecord business=super.getById(businessId);
        if(StringUtils.isNotBlank(licenseImg)){
            business.setLicenseImg(licenseImg);
        }
        if(StringUtils.isNotBlank(institutionalImg)){
            business.setInstitutionalImg(institutionalImg);
        }
        if(StringUtils.isNotBlank(taxImg)){
            business.setTaxImg(taxImg);
        }
        if(StringUtils.isNotBlank(brandRegisterImg)){
            business.setBrandRegisterImg(brandRegisterImg);
        }
        if(StringUtils.isNotBlank(businessBackImg)){
            business.setBusinessBackImg(businessBackImg);
        }
        if(StringUtils.isNotBlank(patentImg)){
            business.setPatentImg(patentImg);
        }
        business.setStatus(1);
        super.updateExceptEmpty(businessId,business);

    }
    /**
     * 个人用户修改个人基础信息
     * @param memberRecordId
     * @param nickName
     * @param sex
     * @param marriage
     * @param birthDay
     * @param idCard
     * @param desc
     */
    public void updateDataMember(Long memberRecordId,String nickName,String sex,String marriage,String phone,String birthDay,String idCard,String desc,String selfAmount){
        SundayMemberRecord member=super.getById(memberRecordId);
        member.setNickName(nickName);
        member.setSex(sex);
        member.setMarriage(marriage);
        member.setPhone(phone);
        member.setBirthDay(birthDay);
        member.setIdCard(idCard);
        member.setDesc(desc);
        member.setSelfAmount(selfAmount);
        super.updateExceptEmpty(memberRecordId,member);
    }
    /**
     * 检测用户是否注册
     * @param phone
     * @param userName
     */
    public void checkMemberIsExist(String phone,String userName){
            Map<String,Object> param = new HashMap<String, Object>();
           if(userName!=null){
               param.put("userName", userName);
               param.put("isDeleted", SundayCommonConstants.NO);
               if(ListUtil.isNotNull(super.list(param))){
                   throw new ErrorException("该用户名已经注册");
               }
           }

           if(phone!=null){
               param.clear();
               param.put("phone", phone);
               param.put("isDeleted", SundayCommonConstants.NO);
               if(ListUtil.isNotNull(super.list(param))){
                   throw new ErrorException("该手机号已经注册");
               }
           }

    }
}
